import axios from 'axios'

// 创建axios实例
const apiClient = axios.create({
  baseURL: 'http://localhost:5001',
  timeout: 60000, // 增加超时时间，特别是对于视频处理
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 可以在这里添加认证token等
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.error('响应错误:', error)
    return Promise.reject(error)
  }
)

// 文件上传和检测API
export const upload = {
  // 图片检测
  detectImage: (formData) => {
    return apiClient.post('/api/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      // 上传进度监控
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          console.log(`图片上传进度: ${percentCompleted}%`)
        }
      }
    })
  },
  
  // 视频处理
  processVideo: (formData) => {
    return apiClient.post('/api/upload/video', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      // 上传进度监控
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          console.log(`视频上传进度: ${percentCompleted}%`)
        }
      }
    })
  },
  
  // 批量图片上传
  batchUpload: (formData) => {
    return apiClient.post('/api/upload/batch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      // 上传进度监控
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          console.log(`批量上传进度: ${percentCompleted}%`)
        }
      }
    })
  },
  
  // 分析网络图片URL
  analyzeImageUrl: (data) => {
    return apiClient.post('/api/upload/analyze-url', data, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
  }
}

export default {
  upload
}